package com.example.wanandroid_copy2.common.login

import android.content.Context
import com.example.wanandroid_copy2.common.collect.CollectListener
import com.example.wanandroid_copy2.common.constant.Constant
import com.example.wanandroid_copy2.common.utils.Preference
import com.example.wanandroid_copy2.ui.collect.data.model.CollectState
import com.example.wanandroid_copy2.ui.login.data.model.LoginState
import com.example.wanandroid_copy2.ui.login.data.model.LoginSucState
import com.example.wanandroid_copy2.ui.login.data.model.LogoutState

class UserContext {

    // 登录状态
    private var isLogin : Boolean by Preference(Constant.LOGIN_KEY, false)

    private var mState: UserState = if (isLogin) LoginState() else LogoutState()

    companion object {
        val instance by lazy { UserContext() }
    }

    fun goCollectActivity(context: Context) {
        mState.goCollectActivity(context)
    }

    fun login(context: Context) {
        mState.login(context)
    }

    // 登录成功之后
    fun loginSuccess(userName :String,collectIds: List<Int>?) {
        isLogin =true
        mState = LoginState()
        LoginSucState.notifyLoginState(userName, collectIds)
    }

    // 观察者模式，通知所有的监听器状态改变
    fun collectRefresh(id: Int, originId: Int) {
        CollectState.notifyCollectState(id, originId)
    }

    fun collect(content : Context, position : Int, listener: CollectListener) {
        mState.collect(content, position, listener)
    }

    fun logoutSuccess() {
        isLogin = false
        Preference.clear()
        mState = LogoutState()
        LoginSucState.notifyLoginState("未登录",null)
    }
}